package com.example.bank.service.union;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.bank.dao.ClientDao;
import com.example.bank.dao.UnionDao;
import com.example.bank.dao.UserDao;
import com.example.bank.exception.SystemException;
import com.example.bank.pojo.Union;
import com.example.bank.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.plaf.multi.MultiLabelUI;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author ：Leeziqiang
 * @description：UnionService实现类
 * @date ：2021/12/4 10:03
 */
@Service
@Transactional
public class UnionServiceImpl implements UnionService{

    private static final Logger logger = LoggerFactory.getLogger(UnionServiceImpl.class);
    @Autowired
    private UnionDao unionDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private ClientDao clientDao;

    @Override
    public boolean bind(String userId, String clientId) {
        logger.info("----------业务员{}执行绑定客户操作----------", userDao.findNameById(userId));
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(clientId)) {
            throw new SystemException("param error");
        }
        String id = UUID.randomUUID().toString();
        Union union = new Union(id, userId, clientId);
        int n = unionDao.saveUnion(union);
        if (n > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<String> getClientIds(String userId) {
        if (StrUtil.isEmpty(userId)) {
            throw new SystemException("userid为空");
        }
        // 判断用户身份
        int roleId = userDao.findRoleByUserId(userId);
        List<String> ids = new ArrayList<>();
        // 如果是经理
        if (roleId == 2) {
            // 查询所在银行区域的所有客户
            String bankArea = userDao.findBankAreaById(userId);
            ids = clientDao.listByBankArea(bankArea);
        } else if (roleId == 4) { // 如果是业务管理员
            // 查询名下业务员的客户
            List<User> users = userDao.findByAgentId(userId);
            for (User user : users) {
                if (ObjectUtil.isNotNull(user)) {
                    ids.addAll(unionDao.findClientByUserId(user.getUserId()));
                }
            }
        } else {
            ids = unionDao.findClientByUserId(userId);
        }
        return ids;
    }
}
